package components
{
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.controls.Button;
	import mx.controls.Label;
	import mx.controls.List;
	import mx.controls.RichTextEditor;
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	import mx.controls.ToolTip;
	import mx.core.Application;
	import mx.events.ListEvent;
	import mx.events.ResizeEvent;
	import mx.managers.ToolTipManager;
	
	import nl.wv.extenders.panel.SuperPanel;
	
	import tools.*;
	
	public class Chat{
		private var panel:SuperPanel = new SuperPanel();
		private var tekst:TextArea = new TextArea();
		private var tool:Tool = new Tool();
		private var label1:Label = new Label();
		private var usersList:List = new List();
		private var roomList:List = new List();
		private var delay:Number = 2000; ///////////// OVO SREDITI
		private var idleAfter:Number = 5; //////////// OVO SREDITI
		private var timer:Timer = new Timer(delay);
		private var service:Mysql = new Mysql();
		private var service1:Mysql = new Mysql();
		private var service2:Mysql = new Mysql();
		private var service3:Mysql = new Mysql();
		private var service4:Mysql = new Mysql();
		private var service5:Mysql = new Mysql();
		private var service6:Mysql = new Mysql();
		private var service7:Mysql = new Mysql();
		private var service8:Mysql = new Mysql();
		private var service9:Mysql = new Mysql();
		private var service10:Mysql = new Mysql();
		private var service11:Mysql = new Mysql();
		private var newRoom:Button = new Button();
		private var tekstInput:RichTextEditor = new RichTextEditor();
		
		private var sifraLabel:Label = new Label();
		private var sifraInput:TextInput = new TextInput();
		private var btnSifra:Button = new Button();
		
		private var _sifra:String = "";
		
		private var lastRoomsChanged:String = "";
		private var lastUsersChanged:String = "";
		private var lastChatChanged:String = "";
		
		private var _room:Number;
		
		private var _lastMessage:Number;
		
		private var _xmlRoom:XML;
		
		private var createToolTipUser:Boolean = true;
		private var createToolTipRooms:Boolean =true;
		
		private var tipUser:ToolTip;
		private var tipRooms:ToolTip;
		
		public function Chat(p:SuperPanel){
			panel = p;
			sifraLabel.x = 50;
			sifraLabel.y = 116;
			sifraLabel.text = "Unesite sifru sobe: ";
			sifraInput.x = 180;
			sifraInput.y = 115;
			sifraInput.width = 80;
			sifraInput.displayAsPassword = true;
			btnSifra.x = 50;
			btnSifra.y = 140;
			btnSifra.width = 210;
			btnSifra.label = "OK";
			p.addEventListener(SuperPanel.WINDOW_CLOSED, closeChat);
		}
		
		public function draw():void{
			tekst.x = 10;
			tekst.y = 27;
			tekst.height = panel.height-130;
	 		tekst.width=panel.width-150;
	 		tekst.editable = false;
	 		roomList.width = 115;
	 		roomList.height = (panel.height-95)/2;
	 		roomList.x = panel.width-135;
	 		roomList.y = 27;
	 		roomList.addEventListener(ListEvent.ITEM_ROLL_OVER, overRoomsList);
	 		roomList.addEventListener(ListEvent.ITEM_ROLL_OUT, outRoomsList);
	 		newRoom.width = 115;
	 		newRoom.height = 20;
	 		newRoom.x = panel.width-135;
	 		newRoom.y = 27 + (panel.height-89)/2;
	 		newRoom.label = "Kreiraj Sobu";	 		
	 		usersList.width = 115;
	 		usersList.height = (panel.height-50)/2;
	 		usersList.x = panel.width-135;
	 		usersList.y = 27 + (panel.height-44)/2;
	 		usersList.dataTipField = "@username";
	 		usersList.addEventListener(ListEvent.ITEM_ROLL_OVER, overUserList);
	 		usersList.addEventListener(ListEvent.ITEM_ROLL_OUT, outUserList);
			
			tekstInput.x = -2;
			tekstInput.y = panel.height-100;
			tekstInput.height = 80;
	 		tekstInput.width=panel.width-118;
			
			panel.addChild(tekstInput);
	 		tekstInput.toolbar.removeChild(tekstInput.alignButtons);
	 		tekstInput.toolbar.removeChild(tekstInput.fontFamilyCombo);
	 		tekstInput.toolbar.removeChild(tekstInput.bulletButton);
	 		tekstInput.toolbar.removeChild(tekstInput.linkTextInput);
	 		
			tekstInput.setStyle("headerHeight", 0);
			tekstInput.setStyle("borderThicknessTop", 0);
			tekstInput.setStyle("borderThicknessBottom", 0);
			tekstInput.setStyle("borderAlpha", 0);
			tekstInput.setStyle("dropShadowEnabled", false);
			tekstInput.textArea.height = 38;
			tekstInput.textArea.width = tekstInput.width-32;
			panel.addChild(tekst);
			panel.addChild(usersList);
			panel.addChild(roomList);
			panel.addChild(newRoom);
			panel.addEventListener(ResizeEvent.RESIZE, onResize);
			tekstInput.addEventListener(KeyboardEvent.KEY_DOWN, sendMessage);
			roomList.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, onChatOpen);
			usersList.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, onUserClicked);
			newRoom.addEventListener(MouseEvent.CLICK, onClickNewRoom)
		}
		
		public function onClickNewRoom(e:MouseEvent):void{
			if(!panel.parentApplication.checkExist("NOVA SOBA")){
				var s:SuperPanel;
				panel.parentApplication.panels.push(s = tool.createPanel("NOVA SOBA", 0, 250, 130, 350, 200, true, false, "NovaSoba"));
				panel.parentApplication.addChild(s);
				s.backButton.addEventListener(MouseEvent.CLICK, panel.parentApplication.taskbarButtonClicked);
				s.backButton.addEventListener(MouseEvent.RIGHT_CLICK, panel.parentApplication.taskbarButtonRightClicked);
				var newRoom:NewRoom = new NewRoom(s);
			}
		}
		
		public function onChatOpen(e:ListEvent):void{
			if(!panel.parentApplication.checkExist("CHAT - "+roomList.selectedItem.@naslov)){
				var s:SuperPanel;
				panel.parentApplication.panels.push(s = tool.createPanel("CHAT - "+roomList.selectedItem.@naslov, 0, 330, 280, 300, 150, true, true, "CHAT"));
				panel.parentApplication.addChild(s);
				s.backButton.addEventListener(MouseEvent.CLICK, panel.parentApplication.taskbarButtonClicked);
				s.backButton.addEventListener(MouseEvent.RIGHT_CLICK, panel.parentApplication.taskbarButtonRightClicked);
				var chatComponent:Chat = new Chat(s);
				chatComponent.sifra = roomList.selectedItem.@sifra;
				chatComponent.sifrirano = (roomList.selectedItem.@sifra).toString().length>0;
				chatComponent.room = roomList.selectedItem.@id_soba;
	 			chatComponent.setRooms(_xmlRoom);
			}
		}
		
		public function onUserClicked(e:ListEvent):void{
			if(!panel.parentApplication.checkExist("KORISNIK - "+usersList.selectedItem.@id_username)){
				var s:SuperPanel;
				panel.parentApplication.panels.push(s = tool.createPanel("KORISNIK - "+usersList.selectedItem.@id_username, 0, 330, 220, 250, 120, true, false, "KORISNIK - "+usersList.selectedItem.@id_username));
				panel.parentApplication.addChild(s);
				s.backButton.addEventListener(MouseEvent.CLICK, panel.parentApplication.taskbarButtonClicked);
				s.backButton.addEventListener(MouseEvent.RIGHT_CLICK, panel.parentApplication.taskbarButtonRightClicked);
				var user:User = new User(s);
				user.id = usersList.selectedItem.@id_username;
			}
		}
		
		public function sendMessage(e:KeyboardEvent):void{
			if(e.keyCode==13) {
				var help:String=tekstInput.htmlText;
				if(help.length>0){
					if(tool.checkForCRC(help)){
						tool.createAlert("Greska!", "Rijec 'CRC' se ne smije nalaziti u tekstu!", 200);
					} else {
						help=tool.CodeTekst(tekstInput.htmlText);
            			service3.sql = {type:"INSERT", into:"chat", columns:"soba, poruka, user, datum, vrijeme", values:"@"+room+"@,@"+tool.CodeTekst(tekstInput.htmlText)+"@,@"+panel.parentApplication.username+"@,@"+tool.currentDate()+"@,@"+tool.currentTime()+"@" }; 
						service3.addEventListener(service3.MYSQL_RESULT, onSendMessage);
 						service3.startService();
						service5.sql = {type:"UPDATE", tables:"soba s", s1:"s.zadnjaIzmjenaChat=@"+tool.uniqueNumber()+"@", where:"s.id_soba="+room };
				 		service5.addEventListener(service5.MYSQL_RESULT, onUpdateZadnjaIzmjena);
	 					service5.startService();
 					}
 				} else tool.createAlert("Greska!", "Niste unijeli tekst!", 200); 
			}
		}
		
		public function onUpdateZadnjaIzmjena(e:Event):void{
			//
		}
		
		public function onSendMessage(e:Event):void{
			tekstInput.text = "";
		}
		
		public function onResize(e:ResizeEvent):void{
			tekst.height = panel.height-130;
	 		tekst.width=panel.width-150;
			tekstInput.y = panel.height-100;
	 		tekstInput.width=panel.width-118;
			tekstInput.textArea.width = tekstInput.width-32;
	 		roomList.height = (panel.height-95)/2;
	 		roomList.x = panel.width-135;
	 		usersList.height = (panel.height-50)/2;
	 		usersList.x = panel.width-135;
	 		usersList.y = 27 + (panel.height-44)/2;
	 		newRoom.x = panel.width-135;
	 		newRoom.y = 27 + (panel.height-89)/2;
		}
		
		public function setRooms(xml:XML):void{
			_xmlRoom = xml;
			service7.sql = {type:"SELECT", a1:"a.id_aktivnost", from:"aktivnost a", where:"a.soba="+room+" AND a.user="+panel.parentApplication.username};
	 		service7.addEventListener(service7.MYSQL_RESULT, onDeleteResult);
		 	service7.startService();
			var xmlList:XMLList = xml.children();
			var xmlPom:String = "<root naziv='Sobe' tip='-1'>";
			for (var i:int=0; i<xmlList.length(); i++) {
				if((xmlList[i].sifra).toString().length==0){
					if(xmlList[i].id_soba!=room){
						xmlPom+="<soba id_soba='"+xmlList[i].id_soba+"' naslov='"+xmlList[i].naziv+"' naziv='"+xmlList[i].naziv+"' sifra='"+xmlList[i].sifra+"'></soba>";
					} else xmlPom+="<soba id_soba='"+xmlList[i].id_soba+"' naslov='"+xmlList[i].naziv+"' naziv='-> "+xmlList[i].naziv+"' sifra='"+xmlList[i].sifra+"'></soba>";
				} else {
					if(xmlList[i].id_soba!=room){
						xmlPom+="<soba id_soba='"+xmlList[i].id_soba+"' naslov='"+xmlList[i].naziv+"' naziv='*"+xmlList[i].naziv+"' sifra='"+xmlList[i].sifra+"'></soba>";
					} else xmlPom+="<soba id_soba='"+xmlList[i].id_soba+"' naslov='"+xmlList[i].naziv+"' naziv='-> *"+xmlList[i].naziv+"' sifra='"+xmlList[i].sifra+"'></soba>";
				}
			}
			xmlPom+="</root>";
			roomList.dataProvider = new XML(xmlPom).children();
			roomList.labelField = "@naziv";
			timer.start();
			timer.addEventListener(TimerEvent.TIMER, onTimer);
			getLastChatId();
		}
		
		public function onDeleteResult(e:Event):void{
            if(service7.xml.children().length()==0){
            	service8.sql = {type:"INSERT", into:"aktivnost", columns:"soba, user, datum, vrijeme", values:"@"+room+"@,@"+panel.parentApplication.username+"@,@"+tool.currentDate()+"@,@"+tool.currentTime()+"@" }; 
				service8.addEventListener(service8.MYSQL_RESULT, onInsertActivities);
 				service8.alert = false;
 				service8.startService();
            }
			catchUsers();
		}
		
		public function onInsertActivities(e:Event):void{
			tekst.htmlText+="<b>System</b>:<i>["+tool.currentDate()+"]["+tool.currentTime()+"]</i><br>Welcome to "+panel.title+" room...<br><br>";
			service9.sql = {type:"UPDATE", tables:"soba s", s1:"s.zadnjaIzmjenaUsers=@"+tool.uniqueNumber()+"@", where:"id_soba="+room };
	 		service9.addEventListener(service9.MYSQL_RESULT, onUpdateZadnjaIzmjenaUsers);
	 		service9.startService();
		}
		
		public function onUpdateZadnjaIzmjenaUsers(e:Event):void{
			//
		}
		
		public function onTimer(e:Event):void{
			service.sql = {type:"SELECT", a1:"p.zadnjaIzmjenaRooms", a2:"s.zadnjaIzmjenaChat", a3:"s.zadnjaIzmjenaUsers", from:"podesavanja p, soba s", where:"s.id_soba="+room };
	 		service.addEventListener(service.MYSQL_RESULT, onChangesCheck);
	 		service.startService();
		}
		
		public function onChangesCheck(e:Event):void{
			service1.sql = {type:"UPDATE", tables:"aktivnost a", s1:"a.datum=@"+tool.currentDate()+"@", s2:"a.vrijeme=@"+tool.currentTime()+"@", where:"a.user="+panel.parentApplication.username+" AND a.soba="+room };
	 		service1.addEventListener(service1.MYSQL_RESULT, onWriteActivities);
	 		service1.startService();

			if(service.xml.children().zadnjaIzmjenaRooms!=lastRoomsChanged){
				lastRoomsChanged = service.xml.children().zadnjaIzmjenaRooms;
				service11.sql = {type:"SELECT", a1:"s.id_soba", a2:"s.naziv", a3:"s.sifra", from:"soba s", where:"" };
	 			service11.addEventListener(service6.MYSQL_RESULT, onCatchRooms);
	 			service11.startService();
				// CATCH ROOMS
			}
			if(service.xml.children().zadnjaIzmjenaUsers!=lastUsersChanged){
				lastUsersChanged = service.xml.children().zadnjaIzmjenaUsers;
				catchUsers();
			}
			if(service.xml.children().zadnjaIzmjenaChat!=lastChatChanged){
				lastChatChanged = service.xml.children().zadnjaIzmjenaChat;
				// CATCH CHATS
				service6.sql = {type:"SELECT", a1:"c.poruka", a2:"c.user", a3:"k.username", a4:"c.datum", a5:"c.vrijeme", a6:"c.id_poruka", from:"chat c, korisnik k", where:"k.id_username=c.user AND c.soba="+room+" AND c.id_poruka>"+_lastMessage};
	 			service6.addEventListener(service6.MYSQL_RESULT, onCatchChats);
	 			service6.startService();
			}
		}
		
		public function onCatchChats(e:Event):void{
			var xmlList:XMLList = service6.xml.children();
			for (var i:int=0; i<xmlList.length(); i++) {
				if(xmlList[i].user!=panel.parentApplication.username){
					tekst.htmlText+="<b>"+xmlList[i].username+"</b>:<i>["+xmlList[i].datum+"]["+xmlList[i].vrijeme+"]</i><br>"+tool.DecodeTekst(xmlList[i].poruka)+"<br>";
				} else tekst.htmlText+="<b>"+xmlList[i].username+"</b>:<i>["+xmlList[i].datum+"]["+xmlList[i].vrijeme+"]</i><br>"+tool.DecodeTekst(xmlList[i].poruka)+"<br>"; 
				_lastMessage = xmlList[i].id_poruka; 
			}
		}
			
		public function onWriteActivities(e:Event):void{
		}
		
		public function set room(x:Number):void{
			_room = x;
		}
		
		public function get room():Number{
			return _room;
		}
		
		public function catchUsers():void{
			service2.sql = {type:"SELECT", a1:"a.user", a2:"k.username", from:"aktivnost a, korisnik k", where:"k.id_username=a.user AND a.soba="+room+" AND a.datum=@"+tool.currentDate()+"@ AND a.vrijeme>@"+tool.currentTimeMinus(idleAfter)+"@"};
	 		service2.addEventListener(service2.MYSQL_RESULT, onCatchUsers);
	 		service2.startService();
		}
		
		public function onCatchUsers(e:Event):void{
			var xmlList:XMLList = service2.xml.children();
			var xmlPom:String = "<root naziv='Korisnici' tip='-1'>";
			for (var i:int=0; i<xmlList.length(); i++) {
				if(xmlList[i].user!=panel.parentApplication.username){
					xmlPom+="<korisnik id_username='"+xmlList[i].user+"' username='"+xmlList[i].username+"'></korisnik>";
				} else xmlPom+="<korisnik id_username='"+xmlList[i].user+"' username='-> "+xmlList[i].username+"'></korisnik>"; 
			}
			xmlPom+="</root>";
			usersList.dataProvider = new XML(xmlPom).children();
			usersList.labelField = "@username"; 
		}
		
		public function getLastChatId():void{
			service4.sql = {type:"SELECT", a1:"MAX(c.id_poruka)", from:"chat c", where:""};
	 		service4.addEventListener(service4.MYSQL_RESULT, onGetLastChatId);
	 		service4.startService();
		}
		
		public function onGetLastChatId(e:Event):void{
			_lastMessage = service4.xml.result.MAX_c_id_poruka_;
		}
		
		public function closeChat(e:Event):void{
			service10.sql = {type:"DELETE", from:"aktivnost", where:"soba="+room+" AND user="+panel.parentApplication.username};
	 		service10.addEventListener(service10.MYSQL_RESULT, onInsertActivities);
		 	service10.startService();
		 	timer.stop();
		}
		
		public function onCatchRooms(e:Event):void{
			var xmlList:XMLList = service11.xml.children();
			var xmlPom:String = "<root naziv='Sobe' tip='-1'>";
			for (var i:int=0; i<xmlList.length(); i++) {
				if((xmlList[i].sifra).toString().length==0){
					if(xmlList[i].id_soba!=room){
						xmlPom+="<soba id_soba='"+xmlList[i].id_soba+"' naslov='"+xmlList[i].naziv+"' naziv='"+xmlList[i].naziv+"' sifra='"+xmlList[i].sifra+"'></soba>";
					} else xmlPom+="<soba id_soba='"+xmlList[i].id_soba+"' naslov='"+xmlList[i].naziv+"' naziv='-> "+xmlList[i].naziv+"' sifra='"+xmlList[i].sifra+"'></soba>";
				} else {
					if(xmlList[i].id_soba!=room){
						xmlPom+="<soba id_soba='"+xmlList[i].id_soba+"' naslov='"+xmlList[i].naziv+"' naziv='*"+xmlList[i].naziv+"' sifra='"+xmlList[i].sifra+"'></soba>";
					} else xmlPom+="<soba id_soba='"+xmlList[i].id_soba+"' naslov='"+xmlList[i].naziv+"' naziv='-> *"+xmlList[i].naziv+"' sifra='"+xmlList[i].sifra+"'></soba>";
				}
			}
			xmlPom+="</root>";
			roomList.dataProvider = new XML(xmlPom).children();
			roomList.labelField = "@naziv";
		}
		
		public function set sifrirano(x:Boolean):void{
			if(x) {
				panel.addChild(sifraLabel);
				panel.addChild(sifraInput);
				panel.addChild(btnSifra);
				btnSifra.addEventListener(MouseEvent.CLICK, onSifraEntered)
			} else draw();
		}
		
		public function onSifraEntered(e:Event):void{
			if(_sifra==sifraInput.text){
				draw();
				panel.removeChild(sifraLabel);
				panel.removeChild(sifraInput);
				panel.removeChild(btnSifra);
			} else tool.createAlert("Greska", "Neispravna sifra!");
		}
		
		public function set sifra(x:String):void{
			_sifra = x;
		}
		
		public function get sifra():String{
			return _sifra;
		}
		
		public function overUserList(event:ListEvent):void{
			if(createToolTipUser){
	 			usersList.selectedIndex = event.rowIndex; 
	            if(panel.x+panel.width+100<panel.parentApplication.screen.width){
	            	tipUser = ToolTipManager.createToolTip(usersList.selectedItem.@username, panel.x+panel.width-20, Application.application.parent.mouseY) as ToolTip;
             	} else tipUser = ToolTipManager.createToolTip(usersList.selectedItem.@username, panel.x+panel.width-135, Application.application.parent.mouseY) as ToolTip;
             	createToolTipUser = false;
        	    tipUser.setStyle("backgroundColor",0xFFCC00);
   			}
		}

		public function outUserList(event:ListEvent):void{
			if(!createToolTipUser) ToolTipManager.destroyToolTip(tipUser);
			createToolTipUser = true;
		}
		
		public function overRoomsList(event:ListEvent):void{
			if(createToolTipRooms){
	 			roomList.selectedIndex = event.rowIndex; 
	            if(panel.x+panel.width+100<panel.parentApplication.screen.width){
	            	tipRooms = ToolTipManager.createToolTip(roomList.selectedItem.@naslov, panel.x+panel.width-20, Application.application.parent.mouseY-20) as ToolTip;
             	} else tipRooms = ToolTipManager.createToolTip(roomList.selectedItem.@naslov, panel.x+panel.width-135, Application.application.parent.mouseY) as ToolTip;
             	createToolTipRooms = false;
        	    tipRooms.setStyle("backgroundColor",0xFFCC00);
   			}
		}

		public function outRoomsList(event:ListEvent):void{
			if(!createToolTipRooms) ToolTipManager.destroyToolTip(tipRooms);
			createToolTipRooms = true;
		}
	}
}